package com.menghao.rpc.spring;

import com.menghao.rpc.provider.model.RpcResponse;
import com.menghao.rpc.serialize.ObjectInput;
import com.menghao.rpc.serialize.ObjectOutput;
import com.menghao.rpc.serialize.hessian.HessianObjectInput;
import com.menghao.rpc.serialize.hessian.HessianObjectOutput;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;

/**
 * <p>RpcResponse消息转换器.<br>
 *
 * @author MarvelCode.
 */
public class RpcResponseConvert extends AbstractHttpMessageConverter<RpcResponse> {

    public RpcResponseConvert(MediaType supportedMediaType) {
        super(supportedMediaType);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return RpcResponse.class.isAssignableFrom(clazz);
    }

    @Override
    protected RpcResponse readInternal(Class<? extends RpcResponse> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        ObjectInput input = new HessianObjectInput(inputMessage.getBody());
        return (RpcResponse) input.readObject(RpcResponse.class);
    }

    @Override
    protected void writeInternal(RpcResponse rpcRequest, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        ObjectOutput output = new HessianObjectOutput(outputMessage.getBody());
        output.writeObject(rpcRequest);
        output.flush();
    }
}
